import React, {forwardRef, useEffect, useImperativeHandle, useMemo, useState} from "react";
import {Text, View, TouchableOpacity, TouchableWithoutFeedback} from "react-native";
import { Calendar, LocaleConfig } from "react-native-calendars";
import { /*RFValue*/ } from "react-native-responsive-fontsize";
import { useTheme } from "styled-components";
import moment from "moment";
import * as S from "../Common/styles";

LocaleConfig.locales["zh"] = {
    monthNames: [
        "一月",
        "二月",
        "三月",
        "四月",
        "五月",
        "六月",
        "七月",
        "八月",
        "九月",
        "十月",
        "十一月",
        "十二月",
    ],
    monthNamesShort: [
        "一月",
        "二月",
        "三月",
        "四月",
        "五月",
        "六月",
        "七月",
        "八月",
        "九月",
        "十月",
        "十一月",
        "十二月",
    ],
    dayNames: [
        "周日",
        "周一",
        "周二",
        "周三",
        "周四",
        "周五",
        "周六",
    ],
    dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
    today: "今天",
};

LocaleConfig.defaultLocale = "zh";

moment.updateLocale("zh-cn", {
    months:
        "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split(
            "_"
        ),
    monthsShort: "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),
    weekdays: "周日_周一_周二_周三_周四_周五_周六".split("_"),
    weekdaysShort: "周日_周一_周二_周三_周四_周五_周六".split("_"),
    weekdaysMin: "日_一_二_三_四_五_六".split("_"),
});

moment.locale("zh-cn");

const CalendarView = forwardRef((props,ref) => {
    const theme = useTheme();
    const [isModalSelectDateOpen, setIsModalSelectDateOpen] = useState(false);
    const [selectedDate, setselectedDate] = useState(
        moment().format("YYYY-MM-DD")
    );

    const [selectedRange, setSelectedRange] = useState({
        startDate: null,
        endDate: null,
        displayedDate: {},
    });

    useImperativeHandle(ref,()=>({
        toggleModal: () => {
            toggleModal();
        },
    }))

    const onDaySelect = (day) => {

        const { dateString } = day;
        let { startDate, endDate, displayedDate } = selectedRange;

        if (startDate && !endDate && dateString >= startDate) {
            // 如果已经选择了开始日期，并且当前选择的日期大于等于开始日期，则设置结束日期
            endDate = dateString;
            displayedDate = getMarkedDates(startDate, endDate);
            props?.selectedRangeCallback&&props?.selectedRangeCallback([startDate, endDate]);
            toggleModal();
        } else {
            // 否则，设置开始日期并重置结束日期
            startDate = dateString;
            endDate = null;
            displayedDate = { [dateString]: { startingDay: true, endingDay: true, color: '#50cebb', textColor: 'white' } };
        }
        setSelectedRange({ startDate, endDate, displayedDate });
    };

    const getMarkedDates = (start, end) => {
        const markedDates = {};
        let currentDate = start;

        while (currentDate <= end) {
            if (currentDate === start) {
                markedDates[currentDate] = { startingDay: true, color: '#50cebb', textColor: 'white' };
            } else if (currentDate === end) {
                markedDates[currentDate] = { endingDay: true, color: '#50cebb', textColor: 'white' };
            } else {
                markedDates[currentDate] = { color: '#70d7c7', textColor: 'white' };
            }
            currentDate = incrementDate(currentDate);
        }

        return markedDates;
    };

    const incrementDate = (date) => {
        const dt = new Date(date);
        dt.setDate(dt.getDate() + 1);
        return dt.toISOString().split('T')[0];
    };


    useEffect(()=>{
        if (selectedDate) {
            const [year, month, day] = selectedDate.split("-");
            const dateBeforeSevenDays = getDateBeforeSevenDays(year, month, day);
            props?.callback&&props.callback(formatDate(dateBeforeSevenDays),[year, month, day].join('.'));
        }
    },[selectedDate])

    const getDateBeforeSevenDays = (year, month, day) => {
        const date = new Date(year, month - 1, day);
        date.setDate(date.getDate() - 6);
        return date;
    }

    const formatDate = (date) => {
        let month = '' + (date.getMonth() + 1),
            day = '' + date.getDate(),
            year = date.getFullYear();
        if (month.length < 2)
            month = '0' + month;
        if (day.length < 2)
            day = '0' + day;
        // return [month, day].join('.');
        return [year, month, day].join('.');
    }

    function toggleModal() {
        setIsModalSelectDateOpen(!isModalSelectDateOpen);
    }
    return (
        <View>
            <S.StyledModal
                visible={isModalSelectDateOpen}
                animationType="fade"
                onRequestClose={toggleModal}
                presentationStyle="overFullScreen"
                transparent
            >
                <TouchableWithoutFeedback onPress={toggleModal}>
                    <S.ModalOverlay>
                        <S.ModalContent>
                            <S.CalendarWrapper>
                                <Calendar
                                    markingType={'period'}
                                    style={{
                                        alignItems: "center",
                                        justifyContent: "center",
                                    }}
                                    theme={{
                                        "stylesheet.calendar.main": {
                                            dayContainer: {
                                                width: /*RFValue*/(44),
                                                height: /*RFValue*/(44),
                                                fontSize: /*RFValue*/(24),
                                                alignItems: "center",
                                                justifyContent: "center",
                                                marginHorizontal: /*RFValue*/(2),
                                            },
                                        },
                                        "stylesheet.calendar.header": {
                                            monthText: {
                                                fontSize: /*RFValue*/(20),
                                                fontFamily: "HarmonyOS_Sans_SC_Regular",
                                                color: "rgba(0, 0, 0, 1)",
                                            },
                                            arrow: {
                                                height: /*RFValue*/(24),
                                            },
                                            arrowImage: {
                                                tintColor: "rgba(67, 113, 177, 1)",
                                                height: /*RFValue*/(24),
                                            },
                                            week: {
                                                width: "100%",
                                                paddingLeft: /*RFValue*/(20),
                                                marginTop: /*RFValue*/(7),
                                                marginBottom: /*RFValue*/(13),
                                                flexDirection: "row",
                                                justifyContent: "space-between",
                                            },
                                            dayHeader: {
                                                marginTop: 2,
                                                marginBottom: 7,
                                                textAlign: "center",
                                                fontSize: /*RFValue*/(13),
                                                fontFamily: "HarmonyOS_Sans_SC_Regular",
                                                fontWeight: 400,
                                                color: "rgba(60, 60, 67, 0.3)",
                                            },
                                        },
                                        "stylesheet.day.basic": {
                                            base: {
                                                width: /*RFValue*/(44),
                                                height: /*RFValue*/(44),
                                                borderRadius: /*RFValue*/(22),
                                                alignItems: "center",
                                                justifyContent: "center",
                                            },
                                            text: {
                                                fontSize: /*RFValue*/(19),
                                                fontFamily: "HarmonyOS_Sans_SC_Regular",
                                                fontWeight: 400,
                                                color: "rgba(0, 0, 0, 1)",
                                            },
                                            selected: {
                                                backgroundColor: "rgba(78, 112, 172, 0.16)",
                                                borderRadius: /*RFValue*/(22),
                                            },
                                            selectedText: {
                                                color: "rgba(0, 0, 0, 1)",
                                            },
                                        },
                                        // "stylesheet."
                                        calendarBackground: theme.colors["background-variant"],
                                    }}
                                    focusable
                                    markedDates={props?.selectPeriod?selectedRange.displayedDate:{[selectedDate]: { selected: true }}}
                                    onDayPress={(date) => {
                                        if (props?.selectPeriod) {
                                            onDaySelect(date);
                                        } else {
                                            setselectedDate(date.dateString);
                                            toggleModal();
                                        }
                                    }}
                                />
                            </S.CalendarWrapper>
                        </S.ModalContent>
                    </S.ModalOverlay>
                </TouchableWithoutFeedback>
            </S.StyledModal>
        </View>
    );
});
export default CalendarView;
